<template>
  <div class="app-container">
    <!-- 预警区 -->
    <div class="forewarning-container">
      <div class="item" v-loading="statLoading">
        <div class="title">申请码数</div>
        <div class="content">{{claimStat.scCount | numFormat}}<span class="unit">次</span></div>
      </div>
      <div class="item" v-loading="statLoading">
        <div class="title">累计申请码数</div>
        <div class="content">{{claimStat.totalScCount | numFormat}}<span class="unit">次</span></div>
      </div>
      <div class="item" v-loading="statLoading">
        <div class="title">扫码人数</div>
        <div class="content">{{claimStat.scanPersonCount | numFormat}}<span class="unit">次</span></div>
      </div>
      <div class="item" v-loading="statLoading">
        <div class="title">累计扫码人数</div>
        <div class="content">{{claimStat.totalScanPersonCount | numFormat}}<span class="unit">次</span></div>
      </div>
    </div>
    <!-- 条件过滤区 -->
    <div class="filter-container">
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-title">场所名称：</span>
            <el-input placeholder="请输入场所名称" size="small"
                class="search-item" v-model="searchObj.csName"/>
        </div>
        <div class="filter-item">
          <span class="filter-title">机构名称：</span>
          <el-input placeholder="所属机构名称" size="small"
                    class="search-item" v-model="searchObj.orgName"/>
        </div>
        <div class="filter-item">
          <span class="filter-title">统计时间：</span>
          <!-- <el-date-picker
            size="small"
            :range-separator="null"
            start-placeholder="请选择时间"
            class="date-range-item"
            format="yyyy-MM-dd"
            type="datetimerange"
            v-model="searchObj.timeRange"
            value-format="yyyy-MM-dd"
          /> -->
          <el-date-picker
            size="small"
            class="search-item date-range-item"
            v-model="searchObj.timeRange"
            type="datetimerange"
            format="yyyy-MM-dd  HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :range-separator="null"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
      </div>
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-title">场所类型：</span>
          <el-cascader
            size="small"
            class="search-item"
            v-model="searchObj.types"
            :options="options"
            :show-all-levels="false"
            :props="{ checkStrictly: true,expandTrigger: 'hover' }"
            clearable></el-cascader>
        </div>
        <div class="filter-item">
          <span class="filter-title">所属区域：</span>
            <el-cascader
              clearable
              size="small"
              class="search-item"
              :props="props"
              @change="handleChange"
              v-model="searchObj.areaIds"
              style="width: 300px"
            ></el-cascader>
        </div>
        <div class="filter-item">
          <el-button size="small" @click="search" class="" type="primary">
            查询
          </el-button>
          <el-button size="small" @click="reset" class="">
            重置
          </el-button>
          <el-button type="primary" size="small" :loading="exportLoading" @click="exportExcel" class="" plain>
            导出
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      size="medium"
      :data="tabItems"
      ref="table"
      style="width: 100%;"
      v-loading="tabLoading"
    >
     <el-table-column label="场所编码" align="center"
        prop="csId"
      />
      <el-table-column label="场所名称" align="center"
        prop="name"
      />
      <el-table-column label="场所类型" align="center"
        prop="type"
      />
      <el-table-column label="所属机构" align="center"
        prop="orgName"
      />
      <el-table-column label="所属区域" align="center"
        prop="areaName"
      />
      <el-table-column
        label="扫码次数/累计扫码次数"
        align="right"
        min-width="90px"
        prop="scanCount"
      >
        <template slot-scope="scope">
          <div>
            <span class="link-color">{{ scope.row.scanCount | numFormat }}</span><br />
            <span class="error-color">{{ scope.row.totalScanCount | numFormat }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="扫码人数/累计扫码人数"
        align="right"
        min-width="90px"
        prop="personCount"
      >
        <template slot-scope="scope">
          <div>
            <span class="link-color">{{ scope.row.personCount | numFormat }}</span><br />
            <span class="error-color">{{ scope.row.totalPersonCount | numFormat }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="红码人数/累计红码人数"
        align="right"
        min-width="90px"
        prop="redCount"
      >
        <template slot-scope="scope">
          <div>
            <span class="link-color">{{ scope.row.redCount | numFormat }}</span><br />
            <span class="error-color">{{ scope.row.totalRedCount | numFormat }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="黄码人数/累计黄码人数"
        align="right"
        min-width="90px"
        prop="orangeCount"
      >
        <template slot-scope="scope">
          <div>
            <span class="link-color">{{ scope.row.orangeCount | numFormat }}</span><br />
            <span class="error-color">{{ scope.row.totalOrangeCount | numFormat }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="灰码人数/累计灰码人数"
        align="right"
        min-width="90px"
        prop="grayCount"
      >
        <template slot-scope="scope">
          <div>
            <span class="link-color">{{ scope.row.grayCount | numFormat }}</span><br />
            <span class="error-color">{{ scope.row.totalGrayCount | numFormat }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination
        :background="true"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-count="pagination.pageCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import areaConvert from '@/utils/areaCodeCov.js';
import { selectCsReportByCs, commAreaUrl, commUserAreaUrl,selectCsInfoClaimStat, exportCsReport, selectCsReportByCsEx  } from '@/http/apiUrls.js';
import areaCodeItems from '@/data/areaCode.js';
import { getDateBefore } from '@/utils/date.js';
export default {
  name: 'PlaceReport',
  data() {
    return {
      tabLoading: false,
      statLoading: false,
      exportLoading: false,
      tableKey: 0,
      pageItems: 10, // 每页查询条数
      pagination: {
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示条数
        pageCount: 1, // 总页数
      },
      claimStat: {
        scCount: null, // 今日申领场所码：单位：个
        totalScCount: null, // 累计申领场所码
        scanPersonCount: null, // 扫码人数
        totalScanPersonCount: null, // 累计扫码人数
      },
      tabItems: [
        {test1: '20220414010',
        test2: '公司前台',
        test3: '办公场所',
        test4: '九黎科技有限公司',
        test5: '贵阳-南明区',
        test6: '31,540,000',
        test7: '31,540,000',
        test8: '27,842,656',
        test9: '42459',
        test10: '42459',
        test11: '42459',
       }
      ],
      searchObj: this.initSearchObj(),
      props: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => {
          const { level } = node;
          console.log('level',level);
          const nodes = [];          
          let type = level == 0 ? null : node.value;
          this.provinceFn(type)
            .then((res) => {
              // 节点数组
              res.map((item) => {
                let obj = {
                  value: item.code,
                  label: item.fullName,
                  leaf: item.level >= 4
                  // leaf: node.level >= 3, 
                };
                nodes.push(obj);
              });
              // resolve 节点返回
              resolve(nodes);
            })
            .catch((error) => {
              console.log(error);
            });
        }
      },
      options: areaCodeItems
    }
  },
  created(){
    let date = getDateBefore(1)
    this.getCsInfoClaimStat({
      startTime: date + ' 00:00:00',
      endTime: date + ' 23:59:59'
    })
    
    this.getData(1, this.pageItems, {
      startTime: date + ' 00:00:00',
      endTime: date + ' 23:59:59'
    }, {})
  },
  methods: {
    initSearchObj(){
      let date = getDateBefore(1)
      return {
        csName: '',
        orgName: '',
        timeRange: [
          date + ' 00:00:00',
          date + ' 23:59:59'
        ],
        areaIds: [],
        types: []
      }
    },
    getSearchObj(){
      let obj = {...this.searchObj};
      if(obj.timeRange && obj.timeRange.length == 2 ){
        obj.startTime = obj.timeRange[0]
        obj.endTime = obj.timeRange[1] 
      }
      const ids = obj.areaIds;
      let areaCode = '';
      if(ids && ids.length > 0){
        areaCode = ids[ids.length-1]
        let likeVal = areaConvert(areaCode);
        obj.areaCode = likeVal
      }
      const types = obj.types;
      let type = '';
      if(types && types.length == 1){
        type = types[0]
        obj.typeFirst = type;
      }else if(types && types.length == 2){
        type = types[1]
        obj.typeSecond = type;
      }

      return obj;
    },
    getCsInfoClaimStat(requestData){
      this.statLoading = true;
      this.$postJson(selectCsReportByCsEx, requestData).then(res => {
        this.statLoading = false;
        if(res){
          this.claimStat = res
        }
      })
    },
    getExtraObj(){
      let obj = this.searchObj;
      let extra = {};
      // if(obj.timeRange && obj.timeRange.length == 2 ){
      //   extra.createTime_ge = obj.timeRange[0]
      //   extra.createTime_le = obj.timeRange[1]
      // }
      // const ids = obj.areaIds;
      // let areaCode = '';
      // if(ids && ids.length > 0){
      //   areaCode = ids[ids.length-1]
      //   let likeVal = areaCode;
      //   console.log(areaCode.lastIndexOf('0000000000'));
      //   console.log(areaCode.lastIndexOf('00000000'));
      //   console.log(areaCode.lastIndexOf('000000'));
      //   if(areaCode.lastIndexOf('0000000000') > -1){
      //     likeVal = areaCode.substring(0, 2);
      //   }else if(areaCode.lastIndexOf('00000000') > -1){
      //     likeVal = areaCode.substring(0, 4);
      //   }else if(areaCode.lastIndexOf('000000') > -1){
      //     likeVal = areaCode.substring(0, 6);
      //   }else{
      //     likeVal = areaCode.substring(0, 9);
      //   }
      //   extra.area_like = likeVal+"%"
      // }
      

      return extra
    },
    search(){
      this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
      this.getCsInfoClaimStat(this.getSearchObj())
    },
    reset(){
      this.searchObj = this.initSearchObj()
      this.getData(1, this.pageItems, this.getSearchObj(), {})
      this.getCsInfoClaimStat(this.getSearchObj())
    },
    getArea(code){
      return new Promise((resolve, reject) => {
        const requestData = {
          parentCode: code
        }
        if(code){
          this.$postJson(commAreaUrl, requestData).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }else{
          this.$postJson(commUserAreaUrl, {}).then(res => {
            if(res){
              resolve(res)
            }else{
              resolve([])
            }
          })
        }
      })
    },
    // 获取省市区街道
    provinceFn(code) {
      // 此处是一个promise 直接返回
      return this.getArea(code);
    },
     // 监听数据变化
    handleChange(value) {
      console.log(value);
    },
    getData(current , size, model, extra){
      let requestData = {
        current,
        size,
        model,
        extra
      }
      this.tabLoading = true;
      this.$postJson(selectCsReportByCs, requestData).then(res => {
        this.tabLoading = false;
        if(res){
          const pagination = {
            currentPage: parseInt(res.current), // 当前页面号
            pageSize: parseInt(res.size), // 每页条目数
            pageCount: parseInt(res.pages), // 总页面数
          }
          this.pagination = pagination;
          this.tabItems = res.records;
        }
      })
    },
    async handleCurrentChange(val) {
      await this.getData(val, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    async handleSizeChange(val) {
      this.pageItems = val
      await this.getData(1, this.pageItems, this.getSearchObj(), this.getExtraObj())
    },
    itemDetail(item){
      console.log(item);
      // this.$router.push({
      //   path: "/eve/bus-user/detail",
      //   query: {id: item.id}
      // })
    },
    exportExcel() {
      let requestData = {
        model: this.getSearchObj()
      }
      // axios({
      //   url: '/api'+exportCsReport,
      //   method: "post",
      //   data: requestData,
      //   noFormat: true,
      //   headers: {
      //     "Content-Type": "application/json; application/octet-stream"
      //   },
      //   responseType: "arraybuffer"
      // }).then(result => {
      //   // if (result.data.error_code) {
      //   //   this.$hMessage.error(result.data.error_message || "导出失败！");
      //   //   return;
      //   // }
      //   var b = new Blob([result.data], { type: "application/vnd.ms-excel" });
      //   // 根据传入的参数b创建一个指向该参数对象的URL
      //   var url = URL.createObjectURL(b);
      //   var link = document.createElement("a");
      //   // 导出的文件名
       
      //   let fileName = "demo.xlsx";
      //   link.download = fileName;
      //   link.href = url;
      //   link.click();
      // });
      this.exportLoading = true
      this.$exportJson(exportCsReport, requestData).then(res => {
        this.exportLoading = false
        if(res){
          console.log(res);
          var b = new Blob([res], { type: "application/vnd.ms-excel" });
          // 根据传入的参数b创建一个指向该参数对象的URL
          var url = URL.createObjectURL(b);
          var link = document.createElement("a");
          // 导出的文件名
        
          let fileName = "场所报表.xlsx";
          link.download = fileName;
          link.href = url;
          link.click();
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.forewarning-container{
  margin-bottom: 20px;
  display: flex;
  // justify-content: center;
  
  .item{
    flex: 1;
    background-color: rgba(242, 242, 242, 0.98);;
    padding: 10px;
    border-radius: 10px;
    margin-right: 20px;
    // width: 20%;
    // min-width: 300px;
    
    .title{
      color: #015478;
      font-size: 1.5rem;
    }

    .content{
      font-size: 1.5rem;
      color: rgba(255, 30, 0, 0.67);
      font-weight: bold;

      .unit{
        font-size: 0.9rem;
        color: black;
        font-weight: normal;
        padding-left: 5px;
      }
    }
  }
}
.app-container {
  .filter-row {
    width: 100%;
    margin-bottom: 8px;
    display: flex;
    .filter-item {
      width: fit-content;
      .filter-title {
        display:inline-block;
        width:100px;
        text-align:right;
        margin-left: 4px;
      }
    }
  }
}
</style>